<?php

namespace addons\TfFutures\backend\controllers;

use addons\TfFutures\services\OrderService;
use common\helpers\ArrayHelper;
use yii\data\Pagination;
use yii;
use common\components\Curd;
use addons\TfFutures\common\models\Member;
use addons\TfFutures\common\models\Msg;
use addons\TfFutures\common\models\Logs;
use common\helpers\ExcelHelper;
use common\models\sys\Manager;

class MemberController extends BaseController
{
    use Curd;

    public $modelClass  = Member::class;
    public $modelClass1 = Msg::class;
    public $modelClass2 = logs::class;

    public function actionIndex(){
        $search = Yii::$app->request->get('keyword','');
        $data   = $this->modelClass::find()
            ->joinWith('member_info')
            ->where(['>=', $this->modelClass::tableName().'.status', 0]);
        $daili = Manager::find()->select("rf_sys_manager.id,rf_sys_manager.username")->join('LEFT JOIN','rf_common_auth_assignment','rf_sys_manager.id=rf_common_auth_assignment.user_id')->where(["rf_common_auth_assignment.role_id"=>4])->asArray()->all();
        $daili = ArrayHelper::map($daili,"username","id");
        $id = Yii::$app->user->id;  //当前登录id
        if (!empty($search)) {
            $data->andFilterWhere(['or',['like','rf_member.username',$search],['like','rf_member.mobile',$search]]);
        }
        if(in_array($id,$daili)){
            $data->andFilterWhere(['daili' => $id]);
        }
        $pages  = new Pagination(['totalCount' => $data->count(), 'pageSize' => $this->pageSize]);
        $models = $data->offset($pages->offset)
            ->orderBy('id desc')
            ->limit($pages->limit)
            ->all();
        $model = [];
        foreach ($models as $k => $v){
            $model[$k]       = array_merge(ArrayHelper::toArray($v),OrderService::loadStatic($v['member_id'], $v['price']));
            $model[$k]['username'] = $v->member_info['username'];
        }
        //总余额
        $member = Member::find()->select('sum(price) as price,sum(price_occupy) as price_occupy,sum(price_profit) as price_profit,sum(price_loss) as price_loss, sum(price_blocked) as price_blocked')->one();
        return $this->render($this->action->id, [
            'models' => $model,
            'pages'  => $pages,
            'keyword'=> $search,
            'member' => $member
        ]);
    }

    public function actionExcel()
    {
        $model = $this->modelClass::find()
                                  ->where(['>', 'id', 0])
                                  ->all();
        if (empty($model)) {
            \yii::$app->session->setFlash('error', '没有数据可以被导出');

            return $this->render('index');
        }
        $header = [
            ['订单ID', 'id', 'text'],
            ['用户名', 'user_name', 'text'],
            ['余额', 'price', 'text'],
            ['占用', 'price_occupy', 'text'],
            ['冻结', 'price_blocked', 'text'],
            ['盈利', 'price_profit', 'text'],
            ['亏损', 'price_loss', 'text'],
        ];
        foreach ($model as $item) {
            $list [] = [
                'id'            => $item->id,
                'user_name'     => $item->member_info['username'],
                'price'         => $item->price,
                'price_occupy'  => $item->price_occupy,
                'price_blocked' => $item->price_blocked,
                'price_profit'  => $item->price_profit,
                'price_loss'    => $item->price_loss,
            ];
        }

        return ExcelHelper::exportData($list, $header);
    }

    /**
     * ajax编辑/创建
     *
     * @return mixed|string|\yii\web\Response
     * @throws \yii\base\ExitException
     */
    public function actionAjaxEdit()
    {
        $id = Yii::$app->request->get('id');
        $model = $this->modelClass::findOne($id);

        // ajax 校验
        $this->activeFormValidate($model);
        if ($model->load(Yii::$app->request->post())) {

            return $model->save()
                ? $this->redirect(['index'])
                : $this->message($this->getError($model), $this->redirect(['index']), 'error');
        }

        return $this->renderAjax($this->action->id, [
            'model' => $model,
        ]);
    }
    /**
     * 赠金
     *
     * @return string
     */
    public function actionGift($id)
    {
        $model = Member::find()
                       ->where(['member_id' => $id])
                       ->one();
        if (Yii::$app->request->isPost) {
           
            $money        = Yii::$app->request->post('price');
            if(!is_numeric($money)){
            	return $this->message("请输入正确的资金格式",$this->redirect('index'),'error');
            }
            if($money > 100000000){
            	return $this->message("赠金数额过大",$this->redirect('index'),'error');
            }

//            $res = OrderService::loadStatic($id,$model->price);
//            $used_money = bcsub($model->price,bcadd($res['order_deposit'],$res['order_overfee'],4),4);
            if( bcadd($model->price,$money,4) < 0 ){
            	$model->price = bcsub($model->price, abs($money), 4);
            	if($model->price < 0){
            		return $this->message("用户可用余额不能为负数",$this->redirect('index'),'error');
            	}
            } else {
            	$model->price = bcadd($model->price, $money, 4);
            }
            if ($model->save()) {
                //添加日志
                Logs::addLogs($model->member_id, '用户赠金', $money, bcsub($model->price, $money, 4),
                    $model->price, '后台管理员给用户赠金' . $money);
            return    $this->message("赠金成功", $this->redirect(['index']), 'success');
            }else {
            return   $this->message('赠金失败', $this->redirect(['index']), 'error');
            }
        }

        return $this->renderAjax('gift', ['model' => $model]);
    }
     /**
     * 提示警告
     *
     * @return string
     */
    public function actionPrompt($id)
    {


        $model = Member::find()
                       ->where(['member_id' => $id])
                       ->one();
        if (Yii::$app->request->isPost) {
           
            $prompt = Yii::$app->request->post('prompt');
            $unwind = Yii::$app->request->post('unwind');
            if(!is_numeric($prompt)||!is_numeric($unwind)){
            	return $this->message("请输入正确的数字",$this->redirect('index'),'error');
            }
            $model->prompt = $prompt;
            $model->unwind = $unwind;
            if ($model->save()) {
               
            return    $this->message("成功", $this->redirect(['index']), 'success');
            }else {
            return   $this->message('失败', $this->redirect(['index']), 'error');
            }
        }

        return $this->renderAjax('prompt', ['model' => $model]);
    }
}